let app = getApp();
import { confirmOrder, makeOrder,getPersonAuth, grantAuthMobile } from "../../../api";
import { disposeData, backMini } from "../../../utils/outData";
import { checkName, checkPhone } from "../../../utils/validate"; 
const util = require('../../../utils/util');
Page({
  data: {
    addressInfo: {
      fullname: '',
      mobilePhone: '',
      address: ''
    },
    goods_id: '',
    setmeal_id: '',
    spec_id: '',
    amount: '',
    isShow: '',
    huabei_stages: '',
    orderInfo: {},
    prov: '',
    city: '',
    area: '',
    email: '',
    remark: '',
    form_id: '',
    order_from: '',
    PackageID: '',
    AccessuserID: '',
    isAgree: false,
    buyOutModal: false,
    orderId: '',
    tradeNo: '',
    qnhlData: {},
    isSelect: true,
    authPhone: '',
    is_renewal: '',
    parent_order_id: '',
    relationId: '',
    contact_name: '',
    contact_mobile: '',
    insurance:'',
    unicom:'',
    em_contact:'',
    em_name:'',
    em_type:'',
    sale_user_id:'',
    certNo:'',
    idInfo:'',
    deposit:'1'
  },
  onLoad(option) {
    console.log(option);
    const { goodsId, setmealId, leaseId, num, huabei_stages, isShow, isRenewal, relationId, parent_order_id, from,pact_type } = option
    this.setData({
      insurance:option.insurance,
      sale_user_id:app.globalData.sale_user_id,
      unicom:option.unicom,
      pact_type:option.pact_type
    })
    const { orderFrom } = app.globalData
    if (orderFrom) {
      this.setData({
        qnhlData: disposeData(),
      })
    }
    const { qnhlData } = this.data
    const authPhone = my.getStorageSync({ key: 'authPhone' }).data;
    this.setData({
      goods_id: goodsId || qnhlData.goodsId,
      setmeal_id: setmealId || qnhlData.setmealId,
      spec_id: leaseId || qnhlData.specId,
      amount: num || qnhlData.amount,
      city: qnhlData.city,
      prov: qnhlData.prov,
      area: qnhlData.area,
      // order_from: orderFrom || from,
      order_from: orderFrom,
      AccessuserID: qnhlData.AccessuserID,
      PackageID: qnhlData.PackageID,
      addressInfo: qnhlData,
      huabei_stages: huabei_stages || qnhlData.huabei_stages,
      isShow,
      isSelect: qnhlData.address ? false : true,
      authPhone,
      is_renewal: isRenewal,
      // relationId: relationId || disposeData().relationId,
      parent_order_id,
      sale_user_id:app.globalData.sale_user_id,
      phone_brand:'',
      location:''
      
    })
    const token = my.getStorageSync({ key: 'token' }).data;
    const that = this

    my.getSystemInfo({
      success: (res) => {
        this.setData({
          phone_brand: res.brand+','+res.model
        })
        console.log(this.data.phone_brand);
      }
    })
    

    if (!token) {
      app.getAuthUser(function (res) {
        if (res) {
          that.createOrders()
        }
      })
    } else {
      that.createOrders()
    }
  },
  onShow() {
    let isAuth = my.getStorageSync({ key: 'isAuthShow' }).data || ''
    const { orderFrom } = app.globalData
    if (isAuth) {
      my.confirm({
        title: '提示',
        content: '当前订单未完成,是否继续',
        confirmButtonText: '是,继续',
        cancelButtonText: '否,回首页',
        success: res => {
          if (res.confirm) {
            if (orderFrom == 'anba') {
              backMini('checkIsvOrder')
            } else {
              my.reLaunch({
                url: '../myOrder/myOrder?order_status=' + 0
              })
            }
          } else {
            if (orderFrom == 'anba') {
              backMini('checkIsvHome')
            } else {
              my.switchTab({ url: '/pages/index/index' })
            }
          }
        },
      });
    }

    getPersonAuth().then(res => {
  
        this.setData({
          idInfo: res
        })
      });
  
      //  console.log(this.data.authPhone);
  },
  onReady(){
    const token = my.getStorageSync({ key: 'token' }).data;
    if(token){
      this.createOrders()
    }
  },

  createOrders() {
    const that = this
    const { goods_id, setmeal_id, spec_id, amount, huabei_stages } = that.data
    let obj = {
      goods_id,
      setmeal_id,
      spec_id,
      amount,
      huabei_stages: huabei_stages || '',
      insurance:this.data.insurance,
      sale_user_id: app.globalData.sale_user_id,
      unicom:this.data.unicom,
      pact_type:this.data.pact_type,
      deposit:this.data.deposit,
    }
    confirmOrder(obj).then(res => {
      this.setData({
        orderInfo: res
      })
    })
  },
  getAuthPhone() {
    const token = my.getStorageSync({ key: 'token' }).data;
    if (!token) {
      app.getAuthUser(function (res) {
        if (res) {
          this.getPhone()
        }
      })
    } else {
      this.getPhone()
    }
  },
  getPhone() {
    const that = this
    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = JSON.parse(res.response).response;
        grantAuthMobile(encryptedData).then(res => {
          if (res) {
            my.setStorage({ key: 'authPhone', data: res.mobile })
            that.setData({ authPhone: res.mobile })
            my.showToast({
              type: 'success',
              content: '获取手机号成功',
            })
            // this.submitOrder()
          } else {
            my.showToast({
              type: 'fail',
              content: '获取手机号失败,请稍后重试',
              duration: 1500,
            })
          }
        })
      },
    });
  },
  onSubmit(e) {
    if (my.canIUse('form.report-submit')) {
        this.setData({
          form_id: e.detail.formId
        })
    }
    // if (!this.data.idInfo.certNo) {
   
    //   // my.navigateTo({
    //   //   url: '../../../pages/userauth/userauth'
    //   // })
    //   my.alert({ content: '请完成身份信息和人脸认证' });
    //  return;
    // }
    // let relationInfo = my.getStorageSync({ key: 'relationInfo' }).data;
    // if(!relationInfo){
    //   my.alert({ content: '请填写紧急联系人' });
    //   my.navigateTo({
    //     url: '../../../pages/userauth/userauth'
    //   })
    //  return;
    // }
    // if(!relationInfo.email){
    //   my.alert({ content: '请填写您的邮箱' });
    //   my.navigateTo({
    //     url: '../../../pages/userauth/userauth'
    //   })
    //  return;
    // }

    if (!this.data.addressInfo.address) {
      my.alert({ content: '请先选择地址' });
      this.selectAddress();
    } else if (!this.data.isAgree) {
      my.alert({ content: '请先阅读并同意协议' });
      this.setData({isAgree:true});
    }else {
      this.submitOrder()
    }
  },
  submitOrder() {
 

    const that = this
    let { goods_id, addressInfo, setmeal_id, spec_id, amount, huabei_stages, prov, city, area, email, remark, form_id, order_from, PackageID, AccessuserID,em_contact,em_name,em_type,emergency_contact,
      orderInfo, is_renewal, relationId, parent_order_id, contact_name, contact_mobile,  
      phone_brand,
      location,pact_type } = that.data
    const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    const number=/^1\d{10}$/
    const { pay_type, contract_type, sign_num, emergency_contact_status } = orderInfo
    // if (email && !(reg.test(email))) {
    //   my.showToast({
    //     content: '邮箱格式有误，请重新输入',
    //     type: 'fail',
    //     duration: 1000
    //   })
    //   return
    // }
     let relationInfo = my.getStorageSync({ key: 'relationInfo' }).data;
  
    // if(em_contact&&!(number.test(em_contact))){
    //   my.showToast({
    //     content: '请重新输入正确的紧急联系人方式！',
    //     type: 'fail',
    //     duration: 1000
    //   })
    //   return
    // }
    // if (emergency_contact_status == 1) {
    //   if (!contact_name) {
    //     my.showToast({
    //       content: '请输入紧急联系人姓名',
    //       type: 'fail',
    //       duration: 1000
    //     })
    //     return
    //   } else if (contact_name && !checkName(contact_name)) {
    //     return;
    //   }
    //   if (!contact_mobile) {
    //     my.showToast({
    //       content: '请输入紧急联系人手机号',
    //       type: 'fail',
    //       duration: 1000
    //     })
    //     return
    //   } else if (!checkPhone(contact_mobile)) {
    //     return;
    //   }
    // }


    // emergency_contact=relationInfo.relationName+','+relationInfo.relation+','+relationInfo.relationPhone;
    // email=relationInfo.email;
    const scene = my.getStorageSync({ key: 'scene' }).data;

    let obj = {
      goods_id, setmeal_id, spec_id, amount,
      prov, city, area, email, remark,
      mobile: addressInfo.mobilePhone,
      realname: addressInfo.fullname,
      address: addressInfo.address,
      form_id,
      order_from,
      huabei_stages,
      PackageID,
      AccessuserID,
      scene:scene,
      insurance:this.data.insurance,
      unicom:this.data.unicom,
      emergency_contact,
      sale_user_id:app.globalData.sale_user_id,
      phone_brand,
      location,
      pact_type
    }
    if (is_renewal) {
      obj['is_renewal'] = is_renewal
    }
    if (relationId) {
      obj['relationId'] = relationId
    }
    if (parent_order_id) {
      obj['parent_order_id'] = parent_order_id
    }
    if (emergency_contact_status == 1) {
      obj['contact_name'] = contact_name
      obj['contact_mobile'] = contact_mobile
    }
    console.log(obj);
    makeOrder(obj).then(res => {
      if (res.order_id) {
        this.setData({
          orderId: res.order_id,
          tradeNo: res.trade_no
        })

        my.setStorage({ key: 'orderId', data: res.order_id })
        // my.reLaunch({
        //   url: '/pagesA/pages/paySuccess/paySuccess?orderId=' + res.order_id
        // })

        my.navigateTo({
          url: '../../../pages/authentication/authentication?orderId=' + res.order_id + '&goodsId=' + goods_id + '&payType=' + pay_type +  '&setmealId=' + that.data.setmeal_id
          + '&specId=' + that.data.spec_id + '&amount=' + that.data.amount 
            + '&contractType=' + contract_type + '&signNum=' + sign_num+'&insurance='+this.data.insurance+ '&type=1'+'&unicom='+this.data.unicom
        })
      } else {
        my.showToast({
          type: 'fail',
          content: res.msg,
          duration: 1500,
        })
      }
    })
  },
  selectAddress: util.throttle(function (e) {
    if (!this.data.qnhlData.address) {
      my.getAddress({
        success: (res) => {
          const { prov, city, area, country, street } = res.result
          this.setData({
            addressInfo: res.result,
            prov, city, area, country, street
          })
        }
      })
    }
  }),
  idInfo(e) {
    my.navigateTo({
      url: '../../../pages/userauth/userauth'
    })
},
  checkBuyout() {
    this.setData({ buyOutModal: !this.data.buyOutModal })
  },
  toLeaseDetails() {
    const { goods_id, setmeal_id, spec_id, amount, orderInfo,pact_type } = this.data
    my.navigateTo({
      url: '../leaseDetails/leaseDetails?goodsId=' + goods_id + '&setmealId=' + setmeal_id + '&specId=' + spec_id +
        '&num=' + amount + '&goodsImg=' + orderInfo.goods_img+'&pact_type=' +pact_type
    })
  },
  closeBuyOutModal() {
    this.setData({ buyOutModal: false })
  },
  onEmail(e) {
    this.setData({ email: e.detail.value })
  },
  onEm_contact(e){
    this.setData({ em_contact:e.detail.value })
  },
  onEm_name(e){
    this.setData({ em_name:e.detail.value })
  },
  onEm_type(e){
    this.setData({ em_type:e.detail.value })
  },
  onRemark(e) {
    this.setData({ remark: e.detail.value })
  },
  onContact(e) {
    if (e.target.dataset.type == "name") {
      this.setData({ contact_name: e.detail.value })
    } else {
      this.setData({ contact_mobile: e.detail.value })
    }
  },
  changeAgree() {
    this.setData({ isAgree: !this.data.isAgree })
  },
  changeAgreea() {
    this.setData({ deposit: '1' })
  },
  changeAgreeb() {
    this.setData({ deposit: '2' })
  },
  checkRent() {
    my.navigateTo({ url: '../print/print' })
  },
  checkPrivacy() {
    my.navigateTo({ url: '../privacy/privacy' })
  },
});
